package movie.ut;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class UTool {

	// 替换字符串
	public static String replace(String src, String regex, String rep) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(src);
		StringBuffer sb = new StringBuffer();
		boolean result = m.find();
		while (result) {
			m.appendReplacement(sb, rep);
			result = m.find();
		}
		m.appendTail(sb);
		// System.out.println(sb.toString());
		return sb.toString();
	}

	// 获取网页
	public static String getHtml(String startUrl) {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpGet httpget = new HttpGet(startUrl);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				System.out.println("Error = " + httpget.getURI());
			} else {
				InputStream is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						is, "UTF-8"));
				try {
					StringBuffer sb = new StringBuffer();
					String str = br.readLine();
					while (str != null) {
						sb.append(str + (char) 13 + (char) 10);
						str = br.readLine();
					}
					return sb.toString();
				} catch (Exception e) {
					httpget.abort();
				} finally {
					try {
						is.close();
					} catch (Exception ignore) {
					}
				}
			}
		} catch (Exception e) {
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return "";
	}

}
